<template>
    <div class="content">
        <hl-segment style="margin-top: 16px" :items="segments" v-model="type"></hl-segment>
        <div class="time-picker van-hairline--top" v-if="type == 1" @click="showTime = true">
            <i class="iconfont icon-shijian"></i>{{time?formatTime(time):'现在出发'}}
        </div>
        <div class="space" v-else>

        </div>
        <hl-field @click="chooseAddress(true)" :show-top-border="true"
                  :value="startLocation.address ? startLocation.address :'定位中...'"></hl-field>
        <hl-field placeholder="去哪儿？" @click="chooseAddress(false)" :value="targetLocation.address"
                  :red="true"></hl-field>

        <p class="price-container van-hairline--bottom" v-if="path">
            <span>约</span><span class="price">{{price}}</span><span>元</span>
        </p>
        <div class="section" style="margin-top: 24px;">
            <button @click="createOrder()" :disabled="canSubmit" class="btn-primary">确定约车</button>
        </div>
        <van-popup v-model="showTime" position="bottom">
            <van-datetime-picker @confirm="onTimeSelect"
                                 v-model="currentDate"
                                 type="datetime"
                                 :min-date="minDate"
            ></van-datetime-picker>
        </van-popup>

    </div>
</template>

<script>
    import HlSegment from "../components/hl-segment";
    import HlField from "../components/HlField";
    import api from '../net/api'
    import url from '../net/url'
    import qs from "qs";
    import dayjs from 'dayjs'

    export default {
        name: "PageTaxi",
        components: {HlField, HlSegment},
        data() {
            return {
                type: 0,
                showTime: false,
                currentDate: new Date(),
                minDate: new Date(),
                segments: [
                    '现在',
                    '预约'
                ],
                path: null,
                time: '',
                chooseStartLocation: {
                    lat: 0,
                    lng: 0,
                    address: "",
                    city: ''
                },
                phone: "",
                name: "",
                targetLocation: {
                    lat: 0,
                    lng: 0,
                    address: "",
                    city: ''
                }
            }
        },
        beforeDestroy() {
            window.eventBus.$off('onCityPickerChoose', this.onCityPickerChoose);

        },

        mounted() {
            window.eventBus.$on('onCityPickerChoose', this.onCityPickerChoose)

        },

        computed: {
            canSubmit() {
                return !(this.path && this.startLocation.lat > 0 && this.startLocation.lng > 0 && this.targetLocation.lat > 0 && this.targetLocation.lng > 0)
            },

            contact() {
                if (this.name && this.phone) {
                    return `${this.name}-${this.phone}`
                } else {
                    return ''
                }
            },

            startLocation() {

                if (!this.chooseStartLocation.address || this.chooseStartLocation.lat === 0 || this.chooseStartLocation.lng === 0) {
                    let location = this.$store.state.location;
                    return location
                } else {
                    return this.chooseStartLocation;
                }
            },
            price() {
                if (this.path) {
                    return this.path.frecastfee
                } else {
                    return 0.00;
                }
            }
        },
        methods: {
            formatTime() {
                return dayjs(this.time).format('YYYY/MM/DD HH:mm:ss')
            },
            onTimeSelect(value) {
                console.log(value)
                this.showTime = false;
                this.time = value;
            },
            createOrder() {
                if (this.path && this.startLocation.lat && this.startLocation.lng && this.targetLocation.lat && this.targetLocation.lng) {
                    let user = this.$store.state.userInfo
                    this.$toast.loading({
                        mask: true,
                        duration: 0,
                        message: '正在下单'
                    })
                    let params = {
                        pathId: this.path.pathid,
                        isCharteredCar: this.type,
                        receiverName: this.name,
                        receiverPhone: this.phone,
                        uid: user.passenger.passengerid,
                        type: 0,
                        triptype: this.type,
                        cartype: 0,
                        reservetime: this.time ? dayjs(this.time).format('YYYY-MM-DD HH:mm') : null,
                        startpointArea: this.startLocation.address,
                        startaddress: this.startLocation.address,
                        targetaddress: this.targetLocation.address,
                        startpoint: `${this.startLocation.lat},${this.startLocation.lng}`,
                        targetpoint: `${this.targetLocation.lat},${this.targetLocation.lng}`,
                    };
                    let socket = this.$store.state.socket;
                    if (socket) {
                        socket.send(JSON.stringify({mid: 101, data: params}))
                    }

                } else {

                }
            },

            onContactChoose(name, phone) {
                this.name = name;
                this.phone = phone;
                this.checkPath();
            },


            onCityPickerChoose(item, from, type) {
                console.log(item)
                if (from == 'taxi') {
                    if (type == 'start') {
                        this.chooseStartLocation = item;
                    } else {
                        this.targetLocation = item;
                    }
                    this.checkPath();
                }
            },

            checkPath() {
                let driving = window.app.$driver;

                if (this.startLocation.lat && this.startLocation.lng && this.targetLocation.lat && this.targetLocation.lng && driving) {
                    this.$toast.loading({
                        mask: true,
                        message: '加载中...',
                        duration: 0
                    })
                    let startLngLat = [this.startLocation.lng, this.startLocation.lat]
                    let targetLngLat = [this.targetLocation.lng, this.targetLocation.lat]

                    driving.search(startLngLat, targetLngLat, (status, result) => {
                        console.log(result);
                        if (status === 'complete') {
                            if (result.routes && result.routes.length) {
                                // 绘制第一条路线，也可以按需求绘制其它几条路线
                                let route = result.routes[0];
                                if (route.distance) {
                                    api.post(url.COUNT_PRICE, qs.stringify({
                                        drivertype: 0,
                                        servicetype: this.type,
                                        cartype: 0,
                                        distance: (route.distance / 1000).toFixed(2),
                                        startpointArea: this.startLocation.address,
                                    })).then(res => {
                                        this.$toast.clear();
                                        this.path = res.data
                                    }).catch(error => {
                                        this.$toast.clear();

                                        this.$dialog.alert({
                                            message: error
                                        }).then(() => {
                                            this.chooseStartLocation = {
                                                lat: 0,
                                                lng: 0,
                                                address: 0
                                            }
                                            this.targetLocation = {
                                                lat: 0,
                                                lng: 0,
                                                address: 0
                                            }
                                        })
                                    })
                                } else {
                                    this.chooseStartLocation = {
                                        lat: 0,
                                        lng: 0,
                                        address: 0
                                    }
                                    this.targetLocation = {
                                        lat: 0,
                                        lng: 0,
                                        address: 0
                                    }
                                }

                            }
                        } else {
                            this.$toast.clear();
                            console.error('获取驾车数据失败：' + result)
                        }
                    })
                    // api.post(url.GET_PATH, qs.stringify({
                    //     startLocation: `${this.startLocation.lng},${this.startLocation.lat}`
                    //     , targetLocation: `${this.targetLocation.lng},${this.targetLocation.lat}`
                    // })).then(res => {
                    //     this.$toast.clear();
                    //     this.path = res.data
                    // }).catch(error => {
                    //     this.$toast.clear();
                    //
                    //     this.$dialog.alert({
                    //         message: error
                    //     }).then(() => {
                    //         this.chooseStartLocation = {
                    //             lat: 0,
                    //             lng: 0,
                    //             address: 0
                    //         }
                    //         this.targetLocation = {
                    //             lat: 0,
                    //             lng: 0,
                    //             address: 0
                    //         }
                    //     })
                    // })
                }
            },

            chooseAddress(start) {
                let type = 'start';
                if (start) {
                    type = 'start'
                } else {
                    type = 'target'
                }
                let query = {from: 'taxi', type: type};
                if (start) {
                    query.area = this.chooseStartLocation.area;
                    query.parent = this.chooseStartLocation.parent;

                } else {
                    if (this.targetLocation.area) {
                        query.area = this.targetLocation.area;
                        query.parent = this.targetLocation.parent;
                    }
                }
                query.showCity = true;
                this.$router.pushTrasnlate({path: "/city", query: query})
            },
        }
    }
</script>

<style scoped lang="less">
    .time-picker {
        height: 40px;
        text-align: center;
        font-size: 14px;
        margin-top: 8px;
        color: #444;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        .icon-shijian {
            font-size: 18px;
            color: #444;
            margin-right: 8px;
        }
    }

    .space {
        margin-top: 12px;
    }

    .price-container {
        font-size: 14px;
        color: #444;
        padding-top: 16px;
        padding-bottom: 16px;
        vertical-align: baseline;
        text-align: center;
        margin: 0;
        .price {
            margin-left: 4px;
            margin-right: 4px;
            font-size: 32px;
            color: #fc1010;
        }
    }

</style>